<script setup lang="tsx">
import Write from './components/Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { onMounted, reactive, ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRoute, useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { FormSchema } from '@/components/Form'
import { ElButton, ElInput, ElTag, ElImage } from 'element-plus'
import {
  addASRApi,
  deleteASRContentApi,
  getASRApi,
  putASRApi,
  putASRErratumApi,
  putASRStatusApi,
  updateASRContentStampApi,
  updateASRStampApi
} from '@/api/check/asr/index'
import { ASRType } from '@/api/check/asr/types'
import { Table, TableColumn } from '@/components/Table'
import Rebut from '@/views/Check/Rebut/Rebut.vue'
import { deleteBox } from '@/utils/deleteMessage'
import { Dialog } from '@/components/Dialog'
import Uploader from '@/components/AttactmentUploader/src/Uploader.vue'

const { emit } = useEventBus()

const { push, go } = useRouter()
const route = useRoute()

const { t } = useI18n()

const currentRow = ref<ASRType>()

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <div class="flex w-full border-unset">
              <div class="w-50">
                <span>SAMC 05-3(2019-12)</span>
                <br />
                <span>
                  状态: <ElTag>{currentRow.value?.status || '未创建'}</ElTag>
                </span>
              </div>
              <div class="font-bold text-xl text-center w-full">
                <span>验收抽样记录</span>
                <br />
                <span>Acceptance Sampling Record(ASR)</span>
              </div>
              <div class="w-50 block">
                <ElButton link onClick={() => rebutAction('detail')}>
                  查看驳回历史
                </ElButton>
                <br />
                <ElButton link onClick={() => (deleteVisible.value = true)}>
                  查看删除记录
                </ElButton>
                <br />
                {/* <ElButton link>查看QAR</ElButton> */}
              </div>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'part_no',
    label: '材料/零件图号:\nMatl/Part No.',
    colProps: {
      span: 12
    }
  },
  {
    field: 'asr_no',
    label: '序号:\nSerial No.',
    colProps: {
      span: 12
    }
  },
  {
    field: 'po_fo_no',
    label: 'PO/FO号:\nPO/FO No.',
    colProps: {
      span: 8
    }
  },
  {
    field: 'packing_sheet_no',
    label: '装箱单号:\nPacking Sheet No.',
    colProps: {
      span: 8
    },
    component: 'Input'
  },
  {
    field: 'mfg_shop_no',
    label: '供应商/车间号:\nSupplier/Shop No.',
    colProps: {
      span: 8
    },
    formItemProps: {
      slots: {
        default: (data) => <ElInput v-model={data.mfg_shop_no} />
      }
    }
  },
  {
    field: '',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          const tableColumns = reactive<TableColumn[]>([
            {
              field: 'index',
              label: '序号\nNo.',
              minWidth: 50,
              slots: {
                default: (scope) => <>{scope.$index + 1}</>
              }
            },
            {
              field: 'characteristic',
              label: '特征\nCharacteristic',
              minWidth: 120
            },
            {
              field: 'irr',
              label: '可靠值\nIRR',
              minWidth: 80
            },
            {
              field: 'dimension',
              label: '尺寸\nDimension',
              minWidth: 200
            },
            {
              field: 'grade',
              label: '等级\nGrade',
              minWidth: 80
            },
            {
              field: 'insp_lot_no',
              label: '检验批次号\nInsp. Lot No.',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row.insp_lot_no}></ElInput>
              }
            },
            {
              field: 'lot_size',
              label: '一批数\nLot Size',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row.lot_size}></ElInput>
              }
            },
            {
              field: 'sample_size',
              label: '样本数量\nSample Size',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row.sample_size}></ElInput>
              }
            },
            {
              field: 'accept_qty',
              label: '接收数量\nAccept Qty',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row.accept_qty}></ElInput>
              }
            },
            {
              field: 'reject_qty',
              label: '拒收数量\nReject Qty',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row.reject_qty}></ElInput>
              }
            },
            {
              field: 'reject_tag_no',
              label: '拒收单号\nRejection Tag No.',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row.reject_tag_no}></ElInput>
              }
            },
            {
              field: 'insp_stamp',
              label: '检验印\nInsp. Stamp',
              minWidth: 120,
              slots: {
                default: (data) =>
                  data.row.insp_stamp ? (
                    <>{data.row.insp_stamp}</>
                  ) : (
                    <ElButton onClick={() => updateASRContentStamp(data.row)}>检验印</ElButton>
                  )
              }
            },
            {
              field: 'action',
              label: '操作\nOperation',
              minWidth: 120,
              slots: {
                default: (data) => (
                  <ElButton link onClick={() => deleteASRContent(data.row)}>
                    删除
                  </ElButton>
                )
              }
            }
          ])
          return <Table data={data.contents} columns={tableColumns} class="w-full" />
        }
      }
    }
  },
  {
    field: 'plan_remark',
    label: '质量计划备注:\nRemark',
    colProps: {
      span: 12
    },
    component: 'Input'
  },
  {
    field: 'insp_remark',
    label: '检验备注:\nRemark',
    colProps: {
      span: 12
    },
    component: 'Input'
  },
  {
    field: 'plan_user',
    label: '质量计划:\nQuality Planning',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: (data) =>
          data.plan_user ? (
            <>{data.plan_user}</>
          ) : (
            <ElButton onClick={() => updateASRStamp(data, 'plan_user')}>刷卡</ElButton>
          )
      }
    }
  },
  {
    field: 'insp_user',
    label: '质量检验:\nQuality Insp.',
    colProps: {
      span: 12
    },
    formItemProps: {
      slots: {
        default: (data) =>
          data.insp_user ? (
            <>{data.insp_user}</>
          ) : (
            <ElButton onClick={() => updateASRStamp(data, 'insp_user')}>刷卡</ElButton>
          )
      }
    }
  },
  {
    field: '',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <div class="leading-5">
              <p>说明Remarks:</p>
              <p>
                1. 编号: 采购件填写QAR-R序号; 制造件填写FO序号。Serial No.: Use QAR-R Serial No. as
                ASR Serial No. for Purchase Item, and FO Serial No. for Fabrication Item.
              </p>
              <p>
                2. 制造商/车间号: 采购件填入制造商名称, SAMC制造件填入车间号。 Supplier/Shop No.:
                Enter supplier code for purchasing product, Enter shop No. for SAMC manufacturing
                parts.
              </p>
              <p>
                3. 等级: 极重要的, 用"C"表示; 主要的, 用"Mj"表示; 次要的, 用"Mi"表示。Grade:
                Critical as 'C', Major as 'Mj', Minor as'Mi'.
              </p>
            </div>
          )
        }
      }
    }
  }
])

// 保存修改
const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    loading.value = true
    try {
      if (currentRow.value?.id) {
        const res = await putASRApi({ ...formData, id: currentRow.value.id })
        if (res) refresh()
      } else {
        const res = await addASRApi({ ...formData })
        if (res) refresh(res.data)
      }
    } finally {
      loading.value = false
    }
  }
}

const updateASRStamp = async (row, type) => {
  const res = await updateASRStampApi(row.id, { type })
  if (res) refresh()
}

const deleteASRContent = async (row) => {
  const res = await deleteBox(deleteASRContentApi, [row.id], t)
  if (res) refresh()
}

const updateASRContentStamp = async (row) => {
  const res = await updateASRContentStampApi([row.id])
  if (res) refresh()
}
// 驳回历史
const rebutVisible = ref(false)
const rebutActionType = ref()
const rebutParams = ref()
const rebutAction = (action: string) => {
  rebutVisible.value = true
  rebutActionType.value = action
  rebutParams.value =
    action === 'add'
      ? {
          rebut_type: 'ASR',
          rebut_form_no: currentRow.value?.asr_no,
          before_status: currentRow.value?.status
        }
      : {
          rebut_type: 'ASR',
          rebut_form_no: currentRow.value?.asr_no
        }
}

// 查看删除记录
const deleteVisible = ref(false)
const delelteColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号\nNo.',
    minWidth: 50,
    slots: {
      default: (scope) => <>{scope.$index + 1}</>
    }
  },
  {
    field: 'characteristic',
    label: '特征\nCharacteristic',
    minWidth: 120
  },
  {
    field: 'irr',
    label: '可靠值\nIRR',
    minWidth: 80
  },
  {
    field: 'dimension',
    label: '尺寸\nDimension',
    minWidth: 200
  },
  {
    field: 'grade',
    label: '等级\nGrade',
    minWidth: 80
  },
  {
    field: 'insp_lot_no',
    label: '检验批次号\nInsp. Lot No.',
    minWidth: 120
  },
  {
    field: 'lot_size',
    label: '一批数\nLot Size',
    minWidth: 120
  },
  {
    field: 'sample_size',
    label: '样本数量\nSample Size',
    minWidth: 120
  },
  {
    field: 'accept_qty',
    label: '接收数量\nAccept Qty',
    minWidth: 120
  },
  {
    field: 'reject_qty',
    label: '拒收数量\nReject Qty',
    minWidth: 120
  },
  {
    field: 'reject_tag_no',
    label: '拒收单号\nRejection Tag No.',
    minWidth: 120
  },
  {
    field: 'insp_stamp',
    label: '检验印\nInsp. Stamp',
    minWidth: 120
  }
])

// 刷新表单
const refresh = async (data: any | undefined = undefined) => {
  const id = data?.id || currentRow.value?.id
  if (id) {
    const res = await getASRApi({ id })
    if (res) currentRow.value = res.data
  }
}

// 更新状态
const updateStatus = async (status: string | undefined = undefined) => {
  const res = await putASRStatusApi({ id: currentRow.value?.id, status })
  if (res) refresh()
}

// 勘误说明
const erratumVisible = ref(false)
const erratumAttachment = ref<string>()
const addErratum = async () => {
  if (erratumAttachment.value) {
    const res = await putASRErratumApi({
      id: currentRow.value?.id,
      erratum_attachment: erratumAttachment.value
    })
    if (res) {
      refresh()
      erratumVisible.value = false
    }
  }
}

// 初始化，获取详情
onMounted(async () => {
  const params = {
    ...route.params,
    ...route.query
  }
  refresh(params)
})

// 监听驳回
useEventBus({
  name: 'addRebut',
  callback: () => {
    refresh()
  }
})
</script>

<template>
  <ContentDetailWrap>
    <p v-if="currentRow && currentRow.erratum_attachment" class="mb-5 text-s" type="danger">
      <a :href="currentRow!.erratum_attachment" target="_blank">勘误说明附件</a>
      {{
        `上传于 ${currentRow!.erratum_datetime} ${currentRow!.erratum_user}`
      }}
    </p>
    <Write ref="writeRef" :form-schema="schema" :current-row="currentRow" class="form-container" />

    <template #header>
      <ElButton @click="go(-1)">
        {{ t('common.back') }}
      </ElButton>
      <ElButton v-if="currentRow?.status == '计划中'" @click="updateStatus()"> 提交检验 </ElButton>
      <ElButton v-if="currentRow?.status == '检验中'" @click="updateStatus()"> 提交审核 </ElButton>
      <ElButton v-if="currentRow?.status == '审核中'" @click="updateStatus()"> 提交归档 </ElButton>
      <ElButton @click="save" v-if="['检验中', '计划中'].includes(currentRow?.status ?? '')">
        保存修改
      </ElButton>
      <ElButton
        @click="rebutAction('add')"
        v-if="['检验中', '审核中'].includes(currentRow?.status ?? '')"
      >
        驳回
      </ElButton>
      <ElButton v-if="currentRow?.status == '归档'" @click="erratumVisible = true">
        勘误说明
      </ElButton>
      <!-- <ElButton>打印</ElButton> -->
    </template>
  </ContentDetailWrap>
  <Rebut v-model="rebutVisible" :action="rebutActionType" :params="rebutParams" />

  <Dialog v-model="deleteVisible" title="删除历史" width="70%" max-height="400px">
    <Table :columns="delelteColumns" :data="currentRow?.delete_contents" />
    <template #footer>
      <ElButton @click="deleteVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
  <Dialog v-model="erratumVisible" title="上传勘误说明" width="70%" max-height="400px">
    <Uploader v-model="erratumAttachment" />
    <div v-if="erratumAttachment" class="w-[40%] m-auto mt-5">
      <ElImage
        :src="erratumAttachment ?? ''"
        fit="cover"
        lazy
        :preview-src-list="[erratumAttachment]"
        preview-teleported
      />
    </div>
    <template #footer>
      <ElButton type="primary" @click="addErratum">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="erratumVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
<style lang="less" scoped>
.form-container {
  border: 3px solid #909399;
  :deep(.el-row) {
    .el-col:first-child {
      border-bottom: 2px solid #909399;
    }
    .el-col:not(:first-child) {
      border: 1px solid #909399;
    }
  }
  :deep(.el-form-item) {
    margin: 18px 0;
    align-items: center;
  }
  :deep(.el-form-item__label) {
    font-size: 13px;
    line-height: 15px !important;
    align-items: center;
    text-align: right;
    white-space: pre-line !important;
  }
  :deep(.el-table .cell) {
    white-space: pre-wrap !important;
    text-align: center;
    font-size: 13px;
  }
}
</style>
@/hooks/event/useEventBus
